#include "app.h"
#include "led.h"
#include "monake.h"
#include "kangtu.h"
#include "wk_gpio.h"
#include "wk_system.h"


TIMER_t time_callback[TIMER_MAX];
static uint8_t mode;

static uint8_t read_terminal_mode(void)
{
	if(gpio_input_data_bit_read(SET1_GPIO_PORT, SET1_PIN) == RESET) {
		wk_delay_ms(100);
		if(gpio_input_data_bit_read(SET1_GPIO_PORT, SET1_PIN) == RESET) {
			return 0;
		}
	}
	
	return 1;
}

static void lift_recvdata_deal(void)
{
	if(mode == MONAKE) {
		monake_recvdata_deal();
	} else {
		kangtu_recvdata_deal();
	}
}

static void lift_recvdata_parse(void)
{
	if(mode == MONAKE) {
		monake_recvdata_parse();
	} else {
		kangtu_recvdata_parse();
	}
}

static void lift_senddata_packaged(void)
{
	if(mode == MONAKE) {
		monake_senddata_packaged();
	} else {
		kangtu_senddata_packaged();
	}
}

static void lift_senddata_transmit(void)
{
	if(mode == MONAKE) {
		monake_senddata_transmit();
	} else {
		kangtu_timebase_computing();
		kangtu_senddata_transmit();
	}
	
}

static void led_relay_deal(void)
{
	if(mode == MONAKE) {
		led_relay_control(0);
	} else {
		led_relay_control(1);
	}
}

static uint8_t timer_callback_register(uint16_t mode, uint16_t cnt, timer_callback func)
{
	for(uint16_t i = 0; i < TIMER_MAX; i++) {
		if(time_callback[i].enable == 0) {
			time_callback[i].enable = 1;
			time_callback[i].count = 0;
			time_callback[i].rate = cnt;
			time_callback[i].mode = mode;
			time_callback[i].callback_fn = func;
			
			return 0;
		}
	}
	
	return 1;
}

void soft_ware_init(void)
{
	mode = read_terminal_mode();
	if(mode == MONAKE) {
		monake_soft_ware_init();
	} else {
		kangtu_soft_ware_init();
	}
	timer_callback_register(PER_SHUT, 350, lift_senddata_packaged);
	timer_callback_register(PER_SHUT, 10, lift_senddata_transmit);
	timer_callback_register(PER_SHUT, 20, lift_recvdata_deal);
	timer_callback_register(PER_SHUT, 10, lift_recvdata_parse);
	timer_callback_register(PER_SHUT, 500, led_relay_deal);
}

void timer_run_out_time(void)
{
	for(uint16_t i = 0; i < TIMER_MAX; i++) {
		if(time_callback[i].enable == 0) {
			
			continue;
		}
		
		if(time_callback[i].count < time_callback[i].rate) {
			time_callback[i].count++;
		} else {
			time_callback[i].count = 0;
			if(time_callback[i].mode == ONE_SHUT) {
				time_callback[i].rate = 0;
				time_callback[i].enable = 0;
			}
			if(time_callback[i].callback_fn != NULL) {
				time_callback[i].callback_fn();
			}
		}
	}
}







